package com.cloudkinto.service.orderrepair.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.cloudkinto.common.DicBusinessConstant;
import com.cloudkinto.common.DicBusinessItemConstant;
import com.cloudkinto.common.common.DateUtils;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.utils.StringsUtil;
import com.cloudkinto.common.utils.dict.StaticDict;
import com.cloudkinto.dao.*;
import com.cloudkinto.entity.*;
import com.cloudkinto.extentity.orderrepair.OrderRepairComponentDto;
import com.cloudkinto.extentity.orderrepair.OrderRepairPageDto;
import com.cloudkinto.extentity.orderrepair.OrderRepairSkuDto;
import com.cloudkinto.service.company.CompanyService;
import com.cloudkinto.service.dic.DicBusinessItemNewService;
import com.cloudkinto.service.dic.DicBusinessItemService;
import com.cloudkinto.service.dic.vo.LanguageValueEntity;
import com.cloudkinto.service.dic.vo.dicBusinessItem.DicBusinessNewEntity;
import com.cloudkinto.service.file.FileMoreService;
import com.cloudkinto.service.file.vo.FileRes;
import com.cloudkinto.service.finance.CostRecordService;
import com.cloudkinto.service.finance.vo.IdAndNameEntity;
import com.cloudkinto.service.operate.OperateRecordService;
import com.cloudkinto.service.operate.vo.OperateRes;
import com.cloudkinto.service.orderrepair.OrderRepairLabelService;
import com.cloudkinto.service.orderrepair.OrderRepairService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;

import com.cloudkinto.service.orderrepair.vo.*;
import com.cloudkinto.service.shop.ShopService;
import com.cloudkinto.service.stock.ProductStockFlowingService;
import com.cloudkinto.service.stock.ProductStockRackService;
import com.cloudkinto.service.stock.StockLogService;
import com.cloudkinto.service.stock.StockRecordService;
import com.cloudkinto.service.storage.StorageService;
import com.cloudkinto.utils.BarCodePdfUtils;
import com.sun.org.apache.xpath.internal.operations.Or;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * service实现类
 * </p>
 *
 * @author hua
 * @since 2023-06-14
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class OrderRepairServiceImpl extends ServiceImpl<OrderRepairDao, OrderRepairDo> implements OrderRepairService {
    @Autowired
    private OrderRepairDao dao;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private DicBusinessItemNewService dicBusinessItemNewService;
    @Autowired
    private DicBusinessItemService dicBusinessItemService;
    @Autowired
    private OrderRepairSkuDao orderRepairSkuDao;
    @Autowired
    private OrderRepairSnDao orderRepairSnDao;
    @Autowired
    private FileMoreService fileMoreService;
    @Autowired
    private OperateRecordService operateRecordService;
    @Autowired
    private StorageService storageService;
    @Autowired
    private StockRecordDao stockRecordDao;
    @Autowired
    private StockLogService stockLogService;
    @Autowired
    private ShopService shopService;
    @Autowired
    private ProductStockDao productStockDao;
    @Autowired
    private ProductStockRackDao productStockRackDao;
    @Autowired
    private ProductStockRackService productStockRackService;
    @Autowired
    private ProductStockFlowingService productStockFlowingService;
    @Autowired
    private OrderRepairLabelService orderRepairLabelService;
    @Autowired
    private OrderBackDao orderBackDao;
    @Autowired
    private StockRecordService stockRecordService;
    @Autowired
    private CostRecordService mCostService;
    @Autowired
    private ProductInfoDao productInfoDao;
    @Autowired
    private ExchangeRateDao exchangeRateDao;
    @Autowired
    private StockLogService stockLogDao;

    @Override
    public SingleResult addInit() {
        Map<String, Object> result = new HashMap<>();
        List<LanguageValueEntity> idAndNameEntities = new ArrayList<>();
        idAndNameEntities.add(new LanguageValueEntity(DicBusinessItemConstant.currency_rmb.intValue(), "人民币"));
        idAndNameEntities.add(new LanguageValueEntity(DicBusinessItemConstant.currency_jpy.intValue(), "日币"));
        result.put("currencyType", idAndNameEntities);
        return SingleResult.success(result);
    }

    @Override
    public void add(OrderRepairAddReq req, Long companyId,Long userId) {
        if (req.getSkuList() == null || req.getSkuList().size() == 0) {
            throw new BizException(SysConstant.No_Data);
        }
        OrderBackDo backDo;
        if (req.getBackId() == null) {
            if (StringUtils.isBlank(req.getBackNo())) {
                backDo = null;
            } else {
                backDo = orderBackDao.selectOne(new LambdaQueryWrapper<OrderBackDo>()
                        .eq(OrderBackDo::getOrderOutNumber, req.getBackNo()).eq(OrderBackDo::getCompanyId, companyId).last(" order by id desc limit 1"));
            }
        } else {
            backDo = orderBackDao.selectOne(new LambdaQueryWrapper<OrderBackDo>()
                    .eq(OrderBackDo::getId, req.getBackId()).eq(OrderBackDo::getCompanyId, companyId));
        }
        OrderRepairDo entityDo = new OrderRepairDo();
        BeanUtils.copyProperties(req, entityDo);
        if (backDo != null) {
            entityDo.setBackId(backDo.getId());
        }
        entityDo.setStatus(StaticDict.Order_Repair_Status_Type.ToCheck.getValue());
        entityDo.setCompanyId(companyId);
        handlerAddBefore(entityDo, userId);
        dao.insert(entityDo);

        //插入操作记录
        operateRecordService.operateAddRecord(StaticDict.Order_Repair_Operate_Type.OrderRepair_Create.getValue(), entityDo.getId(), userId, 9);
        //插入标签
        orderRepairLabelService.updateLabel(entityDo.getId(), req.getLabelIds(), userId);
        //插入skuList
        for (int i = 0; i < req.getSkuList().size(); i++) {
            if (i != 0) {
                break;
            }
            OrderRepairSkuAddReq skuReq = req.getSkuList().get(i);
            this.insertSku(entityDo.getId(), skuReq.getProductId(), skuReq.getQuantity(), userId);
        }
        //插入部件
        if (req.getComponentList() != null) {
            for (OrderRepairComponentAddReq componentReq : req.getComponentList()) {
                this.insertComponent(componentReq, entityDo.getId(), userId);
            }
        }

        //附件处理
        fileMoreService.dealFileList(req.getFileList(), entityDo.getId(), StaticDict.File_Type.RepairAttach.getValue(), userId);

        if (backDo != null) {
            backDo.setStatus(DicBusinessItemConstant.orderBackFinish);
            backDo.setUpdateBy(userId);
            backDo.setUpdateTime(new Date());
            orderBackDao.updateById(backDo);
            operateRecordService.operateAddRecord(SysConstant.OPERATE_DEAL_BACK, backDo.getId(), userId, 8);
        }

    }


    /**
     * 选择标签初始化
     *
     * @param companyId
     * @return
     */
    @Override
    public List<Map> repairCategoryInit(Long companyId) {
        return dicBusinessItemNewService.repairCategoryInit(companyId);
    }

    /**
     * 新增编辑标签
     *
     * @param idAndNameEntity
     * @return
     */
    @Override
    public void addOrUpdateCategory(DicBusinessNewEntity idAndNameEntity) {
        if (idAndNameEntity.getValue() == null || "".equals(idAndNameEntity.getValue())) {
            throw new BizException(SysConstant.OrderRepair_Input_LabelName);
        }

        DicBusinessItemNewDo dicBusinessItemDo = dicBusinessItemNewService.getOne(new LambdaQueryWrapper<DicBusinessItemNewDo>()
                .eq(DicBusinessItemNewDo::getDicItemValue, idAndNameEntity.getValue())
                .eq(DicBusinessItemNewDo::getCompanyId, idAndNameEntity.getCompanyId())
                .and(i -> i.eq(DicBusinessItemNewDo::getDicBusinessId, DicBusinessConstant.repairLabelCanNotEdit).or().eq(DicBusinessItemNewDo::getDicBusinessId, DicBusinessConstant.repairLabelCanEdit))
                .last(" order by id desc limit 1"));
        if (dicBusinessItemDo != null) {
            throw new BizException(SysConstant.OrderRepair_LabelName_Repeat, idAndNameEntity.getValue());
        }
        dicBusinessItemDo = new DicBusinessItemNewDo();
        if (idAndNameEntity.getId() != 0) {
            dicBusinessItemDo.setId(Long.parseLong(idAndNameEntity.getId() + ""));
        }
        dicBusinessItemDo.setDicBusinessId(DicBusinessConstant.repairLabelCanEdit);
        dicBusinessItemDo.setDicItemValue(idAndNameEntity.getValue());
        dicBusinessItemDo.setCompanyId(idAndNameEntity.getCompanyId());
        boolean flag = dicBusinessItemNewService.saveOrUpdate(dicBusinessItemDo);
        if (!flag) {
            throw new BizException(SysConstant.Operate_Failure);
        }
    }

    //新增校验
    private void addCheck(Object req) {

    }

    //做新增之前要执行的业务定制处理
    private void handlerAddBefore(OrderRepairDo entityDo, Long userId) {
        entityDo.setCreateBy(userId);
        entityDo.setCreateTime(new Date());
        entityDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
        OrderRepairDo lastProductDo = dao.selectOne(new LambdaQueryWrapper<OrderRepairDo>()
                .last(String.format(" and DATE_FORMAT(create_time,'%1$s') = '%2$s' order by id desc limit 1", "%Y-%m-%d", DateUtils.dateFormatToString(new Date()))));
        StringBuilder buffer = new StringBuilder("OR");
        buffer.append(DateUtils.dateFormatToString(new Date(), "yyyyMMdd"));
        if (lastProductDo == null) {
            //说明今天是第一单
            buffer.append("0001");
        } else {
            int number = Integer.parseInt(lastProductDo.getRepairNo().substring(10)) + 1;
            buffer.append(number);
            while (buffer.length() < 14) {
                buffer.insert(10, 0);
            }
        }
        entityDo.setRepairNo(buffer.toString());
    }

    //将新增的do转换成要返回的实体
    private Object handlerAddAfter(OrderRepairDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public SingleResult updateInit(Long id) {
        return SingleResult.success(this.detail(id));
    }

    @Override
    public Object update(OrderRepairUpdateReq req, Long userId) {
        OrderRepairDo entityDo = dao.selectById(req.getId());
        if (entityDo == null) {
            throw new BizException(SysConstant.Error_Data_NotExist);
        }
        OrderBackDo backDo = null;
        if (entityDo.getBackId() == null && StringUtils.isNotBlank(req.getBackNo())) {
            backDo = orderBackDao.selectOne(new LambdaQueryWrapper<OrderBackDo>()
                    .eq(OrderBackDo::getOrderOutNumber, req.getBackNo()).eq(OrderBackDo::getCompanyId, entityDo.getCompanyId()));
            if (backDo != null) {
                entityDo.setBackId(backDo.getId());
            }
        }
        BeanUtils.copyProperties(req, entityDo);
        dao.updateById(entityDo);
        //插入操作记录
        operateRecordService.operateAddRecord(StaticDict.Order_Repair_Operate_Type.OrderRepair_Update.getValue(), entityDo.getId(), userId, 9);
        //插入标签
        orderRepairLabelService.updateLabel(entityDo.getId(), req.getLabelIds(), userId);
        //只有待确认 才可以 插入skuList
        if ((StaticDict.Order_Repair_Status_Type.ToCheck.getValue().equals(entityDo.getStatus()))) {
            for (int i = 0; i < req.getSkuList().size(); i++) {
                if (i != 0) {
                    break;
                }
                OrderRepairSkuUpdateReq skuReq = req.getSkuList().get(i);
                if (skuReq.getId() != null) {
                    OrderRepairSkuDo sku = orderRepairSkuDao.selectById(skuReq.getId());
                    sku.setQuantity(skuReq.getQuantity());
                    orderRepairSkuDao.updateById(sku);
                }
                else {
                    this.insertSku(entityDo.getId(), skuReq.getProductId(), skuReq.getQuantity(), userId);
                }
            }
        }
        //维修完成之前才可以 修改插入部件
        if ((StaticDict.Order_Repair_Status_Type.ToCheck.getValue().equals(entityDo.getStatus()) ||
                StaticDict.Order_Repair_Status_Type.Checked.getValue().equals(entityDo.getStatus()) ||
                StaticDict.Order_Repair_Status_Type.Repairing.getValue().equals(entityDo.getStatus()))
                && req.getComponentList() != null) {
            for (OrderRepairComponentUpdateReq componentReq : req.getComponentList()) {
                if (componentReq.getId() != null) {
                    OrderRepairSkuDo component = orderRepairSkuDao.selectById(componentReq.getId());
                    if (component == null) {
                        throw new BizException(SysConstant.No_Data);
                    }
                    BeanUtils.copyProperties(componentReq, component);
                    orderRepairSkuDao.updateById(component);
                } else {
                    this.insertComponent(componentReq, entityDo.getId(), userId);
                }
            }
        }

        //附件处理
        fileMoreService.dealFileList(req.getFileList(), entityDo.getId(), StaticDict.File_Type.RepairAttach.getValue(), userId);
        //维修图片处理
        fileMoreService.dealFileList(req.getRepairFileList(), entityDo.getId(), StaticDict.File_Type.RepairPic.getValue(), userId);


        if (backDo != null) {
            backDo.setStatus(DicBusinessItemConstant.orderBackFinish);
            backDo.setUpdateBy(userId);
            backDo.setUpdateTime(new Date());
            orderBackDao.updateById(backDo);
            operateRecordService.operateAddRecord(SysConstant.OPERATE_DEAL_BACK, backDo.getId(), userId, 8);
        }
        return null;
    }


    /**
     * 删除sku
     */
    @Override
    public void deleteSku(DeleteSkuOrComponentReq req, Long userId) {
        OrderRepairDo entityDo = dao.selectById(req.getId());
        if (entityDo == null) {
            throw new BizException(SysConstant.Error_Data_NotExist);
        }
        if ("sku".equals(req.getType())) {
            //sku 完成指示之前可以删除 sku
            if (!(StaticDict.Order_Repair_Status_Type.ToCheck.getValue().equals(entityDo.getStatus()))) {
                throw new BizException(SysConstant.OrderRepair_Sku_Delete_ERROR);
            }
        } else if ("component".equals(req.getType())) {
            //部件   维修完成之前才可以 删除部件.因为维修完成就需要去 扣减库存
            if (!(StaticDict.Order_Repair_Status_Type.ToCheck.getValue().equals(entityDo.getStatus()) ||
                    StaticDict.Order_Repair_Status_Type.Checked.getValue().equals(entityDo.getStatus()) ||
                    StaticDict.Order_Repair_Status_Type.Repairing.getValue().equals(entityDo.getStatus()))) {
                throw new BizException(SysConstant.OrderRepair_Component_Delete_ERROR);
            }

        } else {
            throw new BizException(SysConstant.No_Data);
        }

        OrderRepairSkuDo et = orderRepairSkuDao.selectOne(new LambdaQueryWrapper<OrderRepairSkuDo>()
                .eq(OrderRepairSkuDo::getRepairId, entityDo.getId()).eq(OrderRepairSkuDo::getId, req.getChildId())
                .eq(OrderRepairSkuDo::getType, req.getType()));
        if (et == null) {
            throw new BizException(SysConstant.No_Data);
        }
        ProductInfoDo productInfoDo = productInfoDao.selectObject(et.getProductId());
        orderRepairSkuDao.deleteById(et.getId());

        //操作日志
        operateRecordService.operateAddRecordAndValue("sku".equals(req.getType()) ? StaticDict.Order_Repair_Operate_Type.OrderRepair_DeleteSku.getValue() : StaticDict.Order_Repair_Operate_Type.OrderRepair_DeleteComponent.getValue(),
                productInfoDo.getCommoditySku(), entityDo.getId(), userId, 9);
    }


    public void insertSku(Long id, Long productId, int quantity,Long userId) {
        if (quantity <= 0) {
            throw new BizException(SysConstant.OrderRepair_Add_Sku);
        }
        OrderRepairSkuDo skuDo = new OrderRepairSkuDo();
        skuDo.setRepairId(id);
        skuDo.setType("sku");
        skuDo.setProductId(productId);
        skuDo.setQuantity(quantity);
        skuDo.setCreateBy(userId);
        skuDo.setCreateTime(new Date());
        orderRepairSkuDao.insert(skuDo);
    }

    public OrderRepairSkuDo insertComponent(OrderRepairComponentAddReq componentReq, Long id, Long userId) {
        OrderRepairSkuDo componentDo = new OrderRepairSkuDo();
        if (componentReq.getShopId() == null) {
            throw new BizException(SysConstant.No_Data);
        }
        BeanUtils.copyProperties(componentReq, componentDo);
        componentDo.setType("component");
        componentDo.setRepairId(id);
        componentDo.setCreateTime(new Date());
        componentDo.setCreateBy(userId);
        orderRepairSkuDao.insert(componentDo);
        return componentDo;
    }

    //做修改之前要执行的业务定制处理
    private void handlerUpdateBefore(OrderRepairDo entityDo, Long userId) {
        entityDo.setUpdateBy(userId);
        entityDo.setUpdateTime(new Date());
    }

    //做修改之后要执行的业务定制处理
    private Object handlerUpdateAfter(OrderRepairDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public int delete(Long id, Long userId) {
        OrderRepairDo entityDo = dao.selectById(id);
        handlerDeleteBefore(entityDo, userId);
        return dao.deleteById(id);
    }

    //做删除之前要执行的业务定制处理
    private void handlerDeleteBefore(OrderRepairDo entityDo, Long userId) {
    }

    @Override
    public OrderRepairDetailRes detail(Long id) {
        OrderRepairDetailRes res = new OrderRepairDetailRes();
        OrderRepairDo entityDo = dao.selectById(id);
        if (entityDo == null) {
            throw new BizException(SysConstant.Error_Data_NotExist);
        }
        BeanUtils.copyProperties(entityDo, res);


        //故障标签id
        List<DicBusinessItemNewDo> itemNewDoList = dao.getLabelItemList(id);
        List<Long> labelIds = itemNewDoList.stream().map(DicBusinessItemNewDo::getId).collect(Collectors.toList());
        res.setLabelIds(labelIds);

        //Sku信息
        res.setSkuList(this.getSkuList(id, entityDo.getCompanyId(), entityDo.getStorageId()));
        //部件信息
        res.setComponentList(this.getComponent(entityDo));

        //附件
        res.setFileList(fileMoreService.getFileList(id, StaticDict.File_Type.RepairAttach.getValue()));
        //维修图片
        res.setRepairFileList(fileMoreService.getFileList(id, StaticDict.File_Type.RepairPic.getValue()));
        //操作日志
        List<OperateRes> operateResList = operateRecordService.getOperateList(entityDo.getId(), 9);
        res.setRecordList(operateResList);
        return res;
    }

    /**
     * 获取部件信息
     *
     * @return
     */
    public List<OrderRepairComponentRes> getComponent(OrderRepairDo et) {
        List<OrderRepairComponentRes> componentList = new ArrayList<>();
        List<OrderRepairComponentDto> componentDtoList = orderRepairSkuDao.getComponentDtoList(et.getId());
        for (OrderRepairComponentDto componentDto : componentDtoList) {
            OrderRepairComponentRes componentRes = new OrderRepairComponentRes();
            BeanUtils.copyProperties(componentDto, componentRes);

            componentList.add(componentRes);
        }
        return componentList;
    }

    /**
     * 获取sku信息
     *
     * @param id
     * @return
     */
    public List<OrderRepairSkuRes> getSkuList(Long id, Long companyId, Long storageId) {
        List<OrderRepairSkuRes> skuList = new ArrayList<>();
        List<OrderRepairSkuDto> skuDoList = orderRepairSkuDao.getSkuDtoList(id);
        for (OrderRepairSkuDto skuDto : skuDoList) {
            OrderRepairSkuRes skuRes = new OrderRepairSkuRes();
            BeanUtils.copyProperties(skuDto, skuRes);
            if (StringUtils.isNotBlank(skuDto.getSnNo()) && skuDto.getSnNo().length() >= 13) {
                skuRes.setSnNo(skuDto.getSnNo().substring(0, 13));
            }
//            skuRes.setGoodQuantity(productStockRackService.getProductList("", null, storageId, companyId).get(0).getGoodQuantity());
            skuList.add(skuRes);
        }
        return skuList;
    }

    //查询明细之后要执行的业务定制处理
    private Object handlerDetailAfter(Object res) {
        return res;
    }

    @Override
    public SingleResult pageInit(Long companyId) {
        Map<String, Object> result = new HashMap<>();
        result.put("statusTypeList", this.getStatusTypeList());
        //产品分类
        result.put("productTypeList", dicBusinessItemService.getDicItemList(DicBusinessConstant.productType));
        result.put("companyList", companyService.getList());
        result.put("storageList", storageService.getJpList());
        Map<String, String> param = new HashMap<>();
        param.put("companyId", companyId + "");
        result.put("shopList", shopService.getList(param).stream().map(shopPageRes -> new IdAndNameEntity(shopPageRes.getId().intValue(), shopPageRes.getShopName())).collect(Collectors.toList()));
        result.put("companyId", companyId);
        return SingleResult.success(result);
    }

    public List<Map<String, String>> getStatusTypeList() {
        List<Map<String, String>> list = new ArrayList<>();
        for (StaticDict.Order_Repair_Status_Type value : StaticDict.Order_Repair_Status_Type.values()) {
            Map<String, String> map = new HashMap<>();
            map.put("id", value.getValue());
            map.put("value", StringsUtil.createI18Message(value.getText()));
            list.add(map);
        }
        return list;
    }

    @Override
    public List<Object> getList(Map<String, String> map) {

        return null;
    }

    @Override
    public PageResult getListPage(Map<String, String> map) {
        IPage<OrderRepairPageDto> page = pageInitDto(map);
        page = dao.listPage(page, map);
        List<OrderRepairPageRes> resList = handlerListAfter(page.getRecords());
        PageResult result = new PageResult(resList, (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        return result;
    }

    private IPage<OrderRepairPageDto> pageInitDto(Map<String, String> map) {
        IPage<OrderRepairPageDto> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }


    //查询分页列表之后对列表数据的处理
    private List<OrderRepairPageRes> handlerListAfter(List<OrderRepairPageDto> list) {
        List<OrderRepairPageRes> result = new ArrayList<>();
        for (OrderRepairPageDto et : list) {
            OrderRepairPageRes res = new OrderRepairPageRes();
            BeanUtils.copyProperties(et, res);
            //故障标签
            List<DicBusinessItemNewDo> itemList = dao.getLabelItemList(et.getId());
            StringBuilder labelName = new StringBuilder();
            for (DicBusinessItemNewDo dicBusinessItemNewDo : itemList) {
                if (labelName.length() > 0) {
                    labelName.append(",");
                }
                labelName.append(StringsUtil.createI18Message(dicBusinessItemNewDo.getDicItemValue()));
            }
            res.setLabelName(labelName.toString());

            //sn码处理一下，只显示第一个
            if (StringUtils.isNotBlank(res.getSnNo()) && res.getSnNo().length() >= 13) {
                res.setSnNo(res.getSnNo().substring(0, 13));
            }
            result.add(res);

            if (et.getCusIndicate() != null && et.getCusIndicate() == 0) {
                LambdaUpdateWrapper<OrderRepairDo> updateWrapper = new LambdaUpdateWrapper<OrderRepairDo>();
                updateWrapper.set(OrderRepairDo::getCusIndicate, 1);
                updateWrapper.eq(OrderRepairDo::getId, et.getId());
                this.update(updateWrapper);
            }
        }
        return result;
    }

    /**
     * 仓库才能标记确认
     */
    @Override
    public void markConfirm(Long id, Long userId) {
        OrderRepairDo et = dao.selectById(id);
        if (et == null) {
            throw new BizException(SysConstant.No_Data);
        }
        if (!StaticDict.Order_Repair_Status_Type.ToCheck.getValue().equals(et.getStatus())) {
            throw new BizException(SysConstant.OrderRepair_Check_Error);
        }
        et.setStatus(StaticDict.Order_Repair_Status_Type.Checked.getValue());
        et.setUpdateBy(userId);
        et.setUpdateTime(new Date());
        dao.updateById(et);

        //操作日志
        operateRecordService.operateAddRecord(StaticDict.Order_Repair_Operate_Type.OrderRepair_MarkConfirm.getValue(), id, userId, 9);
    }


    /**
     * 前端用户 客户指示
     */
    @Override
    public void customerIndicate(CustomerIndicateReq req, Long userId) {
        OrderRepairDo et = dao.selectById(req.getId());
        if (et == null) {
            throw new BizException(SysConstant.No_Data);
        }
        if (!StaticDict.Order_Repair_Status_Type.Repaired.getValue().equals(et.getStatus())) {
            //只有维修完成 才能客户指示
            throw new BizException(SysConstant.OrderRepair_Status_Error);
        }

        //如果维修结果是 无法维修，那么只能废弃
        if (et.getRepairResult() == 1 && req.getCusIndicate() == 0) {
            throw new BizException(SysConstant.OrderRepair_Indicate_ERROR);
        }

        if (req.getCusIndicate() == 0 && req.getGroundShopId() == null) {
            throw new BizException(SysConstant.No_Data);
        }
//        et.setStatus(StaticDict.Order_Repair_Status_Type.Indicate.getValue());
        et.setCusIndicate(req.getCusIndicate());
        et.setUpdateTime(new Date());
        et.setUpdateBy(userId);
//        et.setGroundShopId(req.getGroundShopId());
        dao.updateById(et);
        //操作日志
        operateRecordService.operateAddRecord(req.getCusIndicate() == 0 ? StaticDict.Order_Repair_Operate_Type.OrderRepair_CusIndicate_Grounding.getValue() : StaticDict.Order_Repair_Operate_Type.OrderRepair_CusIndicate_Discard.getValue(),
                req.getId(), userId, 9);
    }


    @Override
    public int getUnIndicateCount(Long companyId) {
        int count = dao.selectCount(new LambdaQueryWrapper<OrderRepairDo>()
                .eq(OrderRepairDo::getCompanyId, companyId)
                .eq(OrderRepairDo::getCusIndicate, 0));
        return count;
    }

}
